<?php
	
    ## creating 
    preg_match('/^(www\.|)(([^\.]+)\..*)$/', $_SERVER['HTTP_HOST'], $matches);
    define ('HOST', $matches[2]);
  
  
    # Runtime path constants definition
    define ('S', DIRECTORY_SEPARATOR);
    define ('ROOT_DIR', str_replace(S . S, S, realpath(dirname(__FILE__) . S . '..') . S));
    define ('ENGINE_DIR', ROOT_DIR . 'engine' . S);
    define ('RUNTIME_DIR', ENGINE_DIR . 'runtime' . S);
    define ('MODEL_DIR', ENGINE_DIR . 'model' . S);
    define ('LIBS_DIR', ENGINE_DIR . 'libs' . S);
    define ('CONFIG_DIR', ROOT_DIR. 'config' . S);
    define ('PUBLIC_DIR', ROOT_DIR . 'public' . S);
    define ('COMPILED_PHP_DIR', ROOT_DIR . 'tmp' . S . 'compiled_php' . S);
    define ('DEV_ENV', 'development');
    
    

    # Core non-class functions
    require(MODEL_DIR . 'core-functions.php');


    # Core models
    require_once(MODEL_DIR . 'Akrudo.php');
    require_once(MODEL_DIR . 'Error.php');
    require_once(MODEL_DIR . 'ActiveRecord.php');
    require_once(MODEL_DIR . 'app_controller.php');
    require_once(MODEL_DIR . 'ActiveCollection.php');
    require_once(MODEL_DIR . 'ActiveRecordCollection.php');
    require_once(MODEL_DIR . 'Column.php');
    require_once(MODEL_DIR . 'Association.php');
    require_once(MODEL_DIR . 'SPYC.php');
    require_once(MODEL_DIR . 'File.php');
    require_once(MODEL_DIR . 'FileHandler.php');
    require_once(MODEL_DIR . 'Inflector.php');
    require_once(MODEL_DIR . 'Result.php');
    require_once(MODEL_DIR . 'PreCompiler.php');
    //require_once(MODEL_DIR . 'AppViewer.php');
    require_once(MODEL_DIR . 'JS.php');
    //require_once(MODEL_DIR . 'Nails.php');
    //require_once(MODEL_DIR . 'ScaffoldedController.php');
    //require_once(MODEL_DIR . 'Dir.php');
    //require_once(MODEL_DIR . 'Common.php');
    //require_once(MODEL_DIR . 'Timer.php');
    //require_once(MODEL_DIR . 'Logger.php');
    
    # Akrudo active data types
    require_once(MODEL_DIR . 'Date.php');
    require_once(MODEL_DIR . 'datatypes/ActiveString.php');



    # PEAR model
    //require_once "Auth.php";
    require_once "Log.php";
    require_once "MDB2.php";



    # Additional libraries / helpers | non model ones
    require_once(LIBS_DIR . 'helpers' . S . '_helpers.php');


    
    # AR constants definitions
    define('first', 'first');
    define('last', 'last');
    define('all', 'all');
    define ('SUCCESS', 1);
    define ('exists', 'exists');
    define ('non_empty', 'non_empty');
    define ('non_blank', 'non_blank');
    define ('email', 'email');
    define ('valid_email', 'valid_email');
    define ('password', 'password');
    define ('valid_password', 'valid_password');
    
    


  
  
  
  
  
#####################################################################################################################################################################################################################  
  
  
### Session start, before sending anything error-producable
  session_start();
  
  
### Akrudo core runtime ###
  $akrudo = new Akrudo();
  $GLOBALS['Akrudo'] =& $akrudo;
  
  
  
### Env setup
  $akrudo->load_config_file('basic');
  
  
  # Checking if basic/environment is present, it's critical
  if (!isset($akrudo->config->basic['environment']))
    # Using standard trigger_error procedure, as logger are not initialized yet
    trigger_error("No 'environment' set up in 'config/basic.yaml'", E_USER_ERROR);
    
  # Checking if basic/compile_php is present, it's critical
  if (!isset($akrudo->config->basic['compile_php']))
    trigger_error("No 'compile_php' set up in 'config/basic.yaml'", E_USER_ERROR);
  
  # Setting up environment public variable and ENV constant
  $akrudo->environment = $akrudo->config->basic['environment'];
  define('ENV', $akrudo->environment);
  $akrudo->compile_php = $akrudo->config->basic['compile_php'];
  define('COMPILE_PHP', $akrudo->compile_php);
  
  # Setting up APP_DIR constant based on ENV
  switch (COMPILE_PHP) {
    case true:
      define ('APP_PREFIX', 'app' . S); 
      define ('APP_DIR', ROOT_DIR . APP_PREFIX); 
    break;
    default:
      define ('APP_PREFIX', ENV . S . 'app' . S);
      define ('APP_DIR', ROOT_DIR . APP_PREFIX); 
    break;
	}
  
#####################################################################################################################################################################################################################
  
### Loggers
  # Loading YAML config file into $akrudo 
  $akrudo->load_config_file('logger');
  
  $logger = &Log::singleton('composite');
  
  ### FileLog configuraton
    $file_conf = array ('lineFormat' => '[%3$s] %4$s');
    $file_log = &Log::singleton('file', ROOT_DIR . 'log' . S . ENV . '.log', '', $file_conf);
    
    # Creating mask from configuration variable
    $levels = array_keys(array_intersect($akrudo->config->logger['file'], array(1)));
    $levels = array_map (array('Akrudo', 'get_error_code'), $levels);
    $levels = array_map (array('Log', 'MASK'), $levels);
    $file_log->setMask(array_sum($levels));
    
    # Logging few first lines
    $file_log->log('', 6);
    $file_log->log('', 6);
    $file_log->log('', 6);
    $file_log->log('', 6);
    
    # Adding logger to parent composite logger
    $logger->addChild($file_log);
  
  
  ### Display log
    $display_conf = array('error_prepend' => '<style>.error br { display: none}</style><span class="error" style="white-space: pre-wrap; font-family: Courier New; font-size: 13px;">',
                          'error_append'  => '</span>',);
    $display_log = &Log::singleton('display', '', 'TEST', $display_conf);
    
    # Adding logger to parent composite logger
    $logger->addChild($display_log);
    
    # Creating mask from configuration variable
    $levels = array_keys(array_intersect($akrudo->config->logger['display'], array(1)));
    $levels = array_map (array('Akrudo', 'get_error_code'), $levels);
    $levels = array_map (array('Log', 'MASK'), $levels);
    $display_log->setMask(array_sum($levels));
  
    
  ### Inactive (for now) loggers
    //$firebug_conf = array('buffering' => true);
    //$firebug_log = &Log::singleton('firebug', '', '', $firebug_conf);
    //$logger->addChild($firebug_log);
    
    //$console_log = &Log::singleton('console', '', 'ident');
    //$logger->addChild($console_log);
  
  
  #$$ Assigning loggers as Akrudo variable
    $akrudo->logger =& $logger;
  

  
  
#####################################################################################################################################################################################################################  

  
  
  
### Once loggers up, we're setting up error handlers and other callbacks
  
  set_error_handler(array('Error', 'handle_php_error'), E_ALL & ~E_NOTICE);
  
  # PEAR Error handling setup
  PEAR::setErrorHandling(PEAR_ERROR_CALLBACK  , array('Error', 'handle_pear_error'));
  
  # MDB2 debugging handling setup
  $options = array('debug' => 1, 'debug_handler' => array('Error', 'handle_mdb2_debug'));
  define ('DB_OPTIONS', serialize($options));
  
  # __autoload function definition, used when class (app/model one) is not loaded   | all others should be loaded manually
  function __autoload($class_name) { ActiveRecord::load_class(APP_DIR . 'model' . S, $class_name); }
  
  
  
### Setting DB options
  
  # Loading YAML config file
  $akrudo->load_config_file('db');
  
  ### DSN set up
    # Going thourgh all of db parameter sets
    foreach ($akrudo->config->db as $environment => $params) {
      
      # Defining '$environment_DSN' constant for each params set
      define(trim($environment) . '_DSN', $params['driver'] . '://' . $params['username'] . ':' . $params['password'] . '@' . $params['hostname'] . '/' . $params['database']);
      
      if ($environment == ENV) {
        # Defining 'DSN' constant for current env's params set
        define('DSN', $params['driver'] . '://' . $params['username'] . ':' . $params['password'] . '@' . $params['hostname'] . '/' . $params['database']);  
      }
    }  
    
    # Checking if base DSN has been created
    if (!defined ('DSN'))
      Akrudo::raise_err("Basic DSN not created. There is no db params set for  '" . ENV . "' in 'db.yaml' config file.");
  
  
  
  
  
#####################################################################################################################################################################################################################    
  
  
  

  
  # Controller runtime
  $akrudo->get_hanlder();
  
  Akrudo::raise_info(' Processing ' . controller . '_controller#' . action . ' (for ' . $_SERVER['HTTP_HOST'] . ' at ' . date("D M d H:i:s T Y") . ")");
  $akrudo->load_controller();
  $akrudo->app_controller->process_one_session_vars();
  $akrudo->app_controller->perform_action();
  $akrudo->app_controller->execute_view();
  
  
  
  
  
  # Ending [info]
  Akrudo::raise_info(" Successfully rendered whole page."); //in xx seconds.");
  
  
  
  
  
  
?>